/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution
{
public:
    ListNode *removeNthFromEnd(ListNode *head, int n)
    {
        ListNode *nplus1ThNodeFromCurrent = head;
        int step = 0;
        ListNode *currentNode = head;
        while (currentNode->next != nullptr) {
            currentNode = currentNode->next;
            if (step >= n) nplus1ThNodeFromCurrent = nplus1ThNodeFromCurrent->next;
            step++;
        }
        // 删除第n个节点
        if (step >= n) {
            nplus1ThNodeFromCurrent->next = nplus1ThNodeFromCurrent->next->next;
        }
            
        else
            head = head->next;
        return head;
    }
};